<?php
/**
 *  Module:  Users
 *  About:   Модель - Группа пользователей
 *  Author:  Vlad Andreev <php.vlad@gmail.com>
 **/

namespace Users;

class UserGroup extends \Control\Model
{
    public function __construct() {
        
        parent::__construct();
        
        $this->repository = $this->em->getRepository('Users\Entities\UserGroup');
        $this->repUserPermission = $this->em->getRepository('Users\Entities\UserPermission');
    }
    
    public function getForm($options = array()) {
        
        $item_id = (!empty($options['values']))
            ? intval($options['values']->id)
            : 0
        ;
        
        $form = new \Control\Forms;
        $form->setTitle($options['title']);
        $form->setTemplate('form-tabs');
        $form->setFormId('form-UserGroup-edit');
        $form->setFormAction('/Users/save/UserGroup/'. $item_id);
        
        $entityFields = array_keys(get_class_vars('Users\Entities\UserGroup'));
        $dataFields = $this->em->getRepository('Data\Entities\DataField')->findBy(
            array('data_name' => 'UserGroup', 'active' => 1),
            array('num' => 'ASC')
        );
        
        $form->addTab('Основное');
        $form->setTabTemplate('form-tab');
        foreach ($dataFields as $field) {
            if (in_array($field->name, $entityFields)) {
                
                $field_name = $field->name;
                
                $field->id = 'Users_'. $field_name;
                $field->caption = $field->title;
                $field->value = (!empty($options['values']->$field_name))
                    ? $options['values']->$field_name
                    : ''
                ;
                
                $form->addTabObject($field);
            }
        }
        
        $form->addTab('Разрешения');
        $form->setTabTemplate('form-tab');
        
        $modules = $this->em->getrepository('Modules\Entities\Module')->findBy(array('active' => 1));
        foreach ($modules as $module) {
            $permissions = $this->repUserPermission->findBy(
                array('module' => $module->name)
            );
            
            if (!empty($permissions)) {
                $link = new \stdClass;
                $link->type     = 'link';
                $link->action   = "if ($('#module_permissions_". $module->name ."').css('display')=='block') $('#module_permissions_". $module->name ."').hide(); else $('#module_permissions_". $module->name ."').show();";
                $link->text     = $module->title;
                $link->style    = "padding:0; border-bottom:1px dashed grey; text-decoration:none";
                
                $form->addTabObject($link);
                
                foreach ($permissions as $permission) {
                    $perm = new \stdClass;
                    $perm->type    = 'checkbox';
                    $perm->id      = $permission->id;
                    $perm->name    = 'permissions['. $permission->id .']';
                    $perm->value   = ($permission->access_mask & $item_id) ? 1 : 0;
                    $perm->label   = $permission->title;
                    $perm->attributes = 'class="checkbox Users_permissions"';
                    
                    $form->addTabObject($perm);
                }
            }
        }
        
        $form->addFooter(array(
            'type'  => 'button',
            'id'    => 'ok',
            'value' => 'Готово',
            'action'=> "acFormSubmit('form-UserGroup-edit', 'listGroups')"
        ));
        $form->addFooter(array(
            'type'  => 'button',
            'id'    => 'save',
            'value' => 'Сохранить',
            'action'=> "acFormSubmit('form-UserGroup-edit')"
        ));
        $form->addFooter(array(
            'type'  => 'button',
            'id'    => 'cancel',
            'value' => 'Отмена',
            'href'  => '#Users/listGroups'
        ));
        
        return $form;
    }
    
    public function save($data, $id = null) {
        
        $id = intval($id);
        
        if(!empty($id))
            $group = $this->find($id);
        
        if(empty($group)) {
            $group = new \Users\Entities\UserGroup;
            
            $group_max = $this->repository->findBy(array(), array('id' => 'DESC'));
            $group->id = (!empty($group_max))
                ? $group_max[0]->id * 2
                : 1
            ;
        }
        
        $entityFields = array_keys(get_object_vars($group));
        
        foreach($data as $field => $value)
            if (in_array($field, $entityFields))
                $group->$field = $value;
        
        $this->em->persist($group);
        $this->em->flush();
        
        // Permissions
        $permissions_active = (!empty($data['permissions'])) ? array_keys($data['permissions']) : array();
        $permissions = $this->em->getRepository('Users\Entities\UserPermission')->findBy(array());
        foreach ($permissions as $permission) {
            $access = ($permission->access_mask & $id);
            
            // need to enable
            if(in_array($permission->id, $permissions_active) && !$access) {
                $permission->access_mask += $id;
                
                $this->em->persist($permission);
                $this->em->flush();
            }
            
            // need to disable
            elseif(!in_array($permission->id, $permissions_active) && $access) {
                $permission->access_mask-= $id;
                
                $this->em->persist($permission);
                $this->em->flush();
            }
        }
        
        return $group->id;
    }
}